const WebSocket = require('ws');
const salary = require("../model/salary");
const user = require('../model/users')
const { add, find, update, del } = require("../server");
const message = require('../model/message')
const punch = require('../model/punch')


// 创建一个WebSocketServer的实例，监听端口8080
const wss = new WebSocket.Server({ port: 8888 });


// 封装listen暴露出去
const listen = () => {
  // 监听连接
  wss.on('connection', (ws) => {
    console.log('可视化大屏连接进来啦...');
    ws.on('message', async (mes) => {
      // console.log(JSON.parse(mes));
      let result = JSON.parse(mes);
      if (result.echarts == 'option') {
        try {
          let data = await find(salary);
          let data1 = await find(user);
          let data3 = await find(message);
          let data4 = await find(punch);
          ws.send(JSON.stringify({
            salary: data,
            user: data1,
            message: data3,
            punch: data4
          }))
          // 向数据库实时查询数据是否有更新
          setInterval(async () => {
            try {
              let data = await find(salary);
              let data1 = await find(user);
              let data3 = await find(message);
              let data4 = await find(punch);
              ws.send(JSON.stringify({
                salary: data,
                user: data1,
                message: data3,
                punch: data4
              }))
            } catch (err) {
              console.log(err);
              let obj = {
                code: 400,
                message: "数据查询失败",
              }
              ws.send(JSON.stringify(obj));
            }
          }, 20000)
        } catch (err) {
          console.log(err);
          let obj = {
            code: 400,
            message: "数据查询失败",
          }
          ws.send(JSON.stringify(obj));
        }
      }
    })
  });
}

module.exports = listen;